package com.sz.sidi.util;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.jdbc.support.rowset.SqlRowSetMetaData;

import com.sz.sidi.exceptions.DaoException;


public class DaoUtil {
	private static final Logger logger = Logger.getLogger(DaoUtil.class);

	

	/**
	 * ResultSet转化为List
	 * 
	 * @param rs
	 *            ResultSet 数据集
	 * @param cls
	 *            Class List中JavaBean的类型
	 * @return List
	 * @throws Exception
	 */
	public static List<Object> convertToList(SqlRowSet rs, Class cls)
			throws SQLException {
		// logger.info("开始转换："+TimeHelper.getCurrentTimeString());
		List<Object> list = new ArrayList<Object>();

		if (rs == null || !rs.next())
			return null;
		do {
			Object obj;
			try {
				obj = cls.newInstance();
			} catch (InstantiationException e) {
				e.printStackTrace();
				throw new DaoException(
						"Method:<arrayToList>:" + e.getMessage(), e);
			} catch (IllegalAccessException e) {
				e.printStackTrace();
				throw new DaoException(
						"Method:<arrayToList>:" + e.getMessage(), e);
			}
			convertToObject(rs, obj);
			list.add(obj);
		} while (rs.next());

		// logger.info("结束转换："+TimeHelper.getCurrentTimeString());
		return list;
	}

	private static boolean convertToObject(SqlRowSet rs, Object obj)
			throws DaoException, SQLException {
		int j = 0;
		Field fieldlist[] = obj.getClass().getDeclaredFields();
		Map<String, String> map = new HashMap<String, String>();
		for (int i = 0; i < fieldlist.length; i++) {
			Field fld = fieldlist[i];
			String fName = fld.getName();
			map.put(fName.toLowerCase(), fName);
		}
		BeanWrapper bwComp = new BeanWrapperImpl(obj);
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		bwComp.registerCustomEditor(Date.class, new CustomDateEditor(
				dateFormat, false));
		SqlRowSetMetaData md = rs.getMetaData();

		for (int i = 0; i < md.getColumnCount(); i++) {
			String columnName = md.getColumnName(i + 1);
			columnName = map.get(columnName.toLowerCase());
			if (columnName == null)
				continue;
			String columnValue = rs.getString(columnName);
			try {
				Field fld = obj.getClass().getDeclaredField(columnName);

				if ((GlobalFun.hasValue(columnName)))
					if ((columnValue != null) && (!columnValue.equals("null"))) {
						if (!fld.getType().equals(String.class)
								&& !GlobalFun.hasValue(columnValue))
							continue;
						if (!fld.getType().equals(java.util.Date.class)
								&& columnValue.trim().equals(""))
							columnValue = null;

						bwComp.setPropertyValue(columnName, columnValue);
					}
				j++;
			} catch (Exception e) {
				logger.error(e.getMessage());
				throw new DaoException("Method:<arrayToObject>类["
						+ obj.getClass().getName() + "]中不存在指定方法:"
						+ e.getMessage(), e);
			}

		}
		return (j > 0);
	}
}